package com.szholly.data.general.interceptor;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.szholly.data.general.interceptor.defulat.*;

/**
 * 类功能说明 定义数据拦截器注册类
 */
public class InterceptorRegister {
	
	/**
	 * 查询拦截
	 */
	public static List<IDbSelectInterceptor> dbSelectInterceptor = new ArrayList<IDbSelectInterceptor>();
	
	/**
	 * 编辑拦截
	 */
	public static List<IDbEditInterceptor> dbEditInterceptor = new ArrayList<IDbEditInterceptor>();

	static {
		// 注册系统默认拦截器
//		RegDbInterceptor(new CodeRuleDbInterceptor()); 				// -100
		RegDbInterceptor(new VersionCheckInterceptor()); 				// -90
		RegDbInterceptor(new UniqueCheckInterceptor()); 				// -80
		RegDbInterceptor(new TreeTableEditInterceptorClass()); 		// -70
		RegDbInterceptor(new ChildTableEditInterceptor()); 				// -60
	}

	/**
	 * 注册编辑拦截接口
	 * @param editInterceptor
	 */
	public static void RegDbInterceptor(IDbInterceptor editInterceptor) {
		if (editInterceptor == null)
			return;

		if (editInterceptor instanceof IDbSelectInterceptor) {
			if (!dbSelectInterceptor.contains((IDbSelectInterceptor) editInterceptor)) {
				dbSelectInterceptor.add((IDbSelectInterceptor) editInterceptor);
				Collections.sort(dbSelectInterceptor, comparator);
			}
		}

		if (editInterceptor instanceof IDbEditInterceptor) {
			if (!dbEditInterceptor.contains((IDbEditInterceptor) editInterceptor)) {
				dbEditInterceptor.add((IDbEditInterceptor) editInterceptor);
				Collections.sort(dbSelectInterceptor, comparator);
			}
		}
	}

	/**
	 * 移除编辑拦截接口
	 * @param editInterceptor
	 */
	public static void RemoveDbInterceptor(IDbInterceptor editInterceptor) {
		if (editInterceptor == null)
			return;

		if (editInterceptor instanceof IDbSelectInterceptor) {
			if (dbSelectInterceptor.contains((IDbSelectInterceptor) editInterceptor)) {
				dbSelectInterceptor.remove((IDbSelectInterceptor) editInterceptor);
				Collections.sort(dbSelectInterceptor, comparator);
			}
		}

		if (editInterceptor instanceof IDbEditInterceptor) {
			if (dbEditInterceptor.contains((IDbEditInterceptor) editInterceptor)) {
				dbEditInterceptor.remove((IDbEditInterceptor) editInterceptor);
				Collections.sort(dbSelectInterceptor, comparator);
			}
		}
	}

	private static Comparator<IDbSelectInterceptor> comparator = new Comparator<IDbSelectInterceptor>() {
		public int compare(IDbSelectInterceptor a, IDbSelectInterceptor b) {
			if (a.getIndex() - b.getIndex() >= 0) {
				return 1;
			} else {
				return -1;
			}
		}
	};
}
